package cn.home.bootstrap.publishsubscribe.topic;

import com.google.common.collect.Maps;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *  发送端和场景4的区别：
 * 1、exchange的type为topic
 * 2、发送消息的routing key不是固定的单词，而是匹配字符串，如"*.lu.#"，*匹配一个单词，#匹配0个或多个单词。
 */
@Slf4j
public class EmitLogTopic {
  private final static String IP = "127.0.0.1";
  private final static int  PORT = 5672;
  private static final String EXCHANGE_NAME = "topic_logs";
  public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost(IP);
      factory.setPort(PORT);
      connection = factory.newConnection();
      channel = connection.createChannel();
      //配置交换器，为topic模式
      channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
      List<String> routeKeys = Arrays.asList("sky.blue.color","orange.yellow.color","cat.annimal","dog.annimal","car.tools.slow","bike.tools.quickly");
      Map<String,String> messages = Maps.newHashMap();
      messages.put("sky.blue.color","sleep in blue sky...");
      messages.put("orange.yellow.color","eat a orange...");
      messages.put("cat.annimal","find a cat...");
      messages.put("dog.annimal","there three dogs....");
      messages.put("car.tools.slow","go to company by car..");
      messages.put("bike.tools.quickly","back home rely on bike...");
      for(String routingKey : routeKeys) {
        String message = messages.get(routingKey);
        //发表消息到指定的交换器的routingKey队列
        channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
        log.info(" [x] Sent routeKey:{}, message:{}", routingKey, message);
      }

    }
    catch  (Exception e) {
      e.printStackTrace();
    }
 /*   finally {
      if (connection != null) {
        try {
          connection.close();
        }
        catch (Exception ignore) {}
      }
    }*/
  }

  private static String getRouting(String[] strings){
    if (strings.length < 1)
    	    return "anonymous.info";
    return strings[0];
  }

  private static String getMessage(String[] strings){
    if (strings.length < 2)
    	    return "Hello World!";
    return joinStrings(strings, " ", 1);
  }

  private static String joinStrings(String[] strings, String delimiter, int startIndex) {
    int length = strings.length;
    if (length == 0 ) return "";
    if (length < startIndex ) return "";
    StringBuilder words = new StringBuilder(strings[startIndex]);
    for (int i = startIndex + 1; i < length; i++) {
        words.append(delimiter).append(strings[i]);
    }
    return words.toString();
  }
}

